var form = layui.form, laydate = layui.laydate, annexList = [], upload = layui.upload, table = layui.table, $ = layui.jquery,
    id = getQueryVariable("id");
layui.use(['tableEdit'], function () {
    let  tableEdit = layui.tableEdit;
    let layer = layui.layer;

    //主表数据
    let detailData = [];
    //产品详情
    let childData = [];

    //仓库信息
    let warehouseNamedData = [];
    let warehouseList = [];

    $(document).ready(function () {
        //1.获取所有下拉框信息
        getSelectData();

        //2.获取详情信息
        getDetailInfo();

        table.reload('storageproductstableid',{data:detailData});
        table.reload('attachmenttableid',{data:annexList});
    });

    //获取详情信息
    function getDetailInfo() {
        //获取详情信息
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:JSON.stringify(id),
            url:"transfer/detail/getTransferDetailInfo",
            async:false,
            success:function(res){
                if(res.status == 200){
                    //主表信息赋值
                    $("#id").val(res.data.id);
                    $("#billNo").val(res.data.billNo);
                    $("#newBillNo").val(res.data.billNo);
                    $("#time").val(res.data.time);
                    $("#warehouseCode").val(res.data.warehouseCode);
                    $("#warehouseName").val(res.data.warehouseName);
                    $("#founder").val(res.data.creator);
                    $("#createDate").val(res.data.createDate);
                    $("#memo").val(res.data.memo);

                    //产品列表信息
                    detailData = res.data.productVos;

                    //附件信息
                    annexList = res.data.annexVos;

                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    }

    //获取所有下拉框信息
    function getSelectData(){
        //获取仓库信息
        $.ajax({
            url:"transfer/getWarehouse",
            async:false,
            success:function(data){
                if(data.status == 200){
                    warehouseList = data.data;
                    for(let i in data.data){
                        let temp = {
                            name : data.data[i].code,
                            value : data.data[i].name
                        };
                        warehouseNamedData.push(temp);
                        $("#warehouseCode").append("<option value=\"" + data.data[i].code + "\">" + data.data[i].name + "</option>");
                    }
                    form.render('select');
                }
            }
        });
    }

    form.render('select');
    //表单初始值，修改时调用
    if (id != "") {
        form.val("editor-form", {
            "emptynumber": "置空单号",
        })
    }
    //监听下拉框
    form.on('select(warehouseCode)', function (data) {
        if(data.value === ""){
            return;
        }
        let name = getWarehouseName(data.value);
        $("#warehouseName").val(name);
        childData = table.cache["thedetailtableid"];
        let oldTransferData =  table.cache["storageproductstableid"];
        if(oldTransferData.length > 0){
            for(let i in oldTransferData){
                oldTransferData[i]["newWarehouseName"] = getWarehouseName(data.value);
                oldTransferData[i]["newWarehouseCode"] = data.value;
            }
            table.reload('storageproductstableid',{data : oldTransferData});
        }else {
            return;
        }

    })

    //根据仓库id获取仓库名称
    function getWarehouseName(code){
        if(warehouseList.length > 0){
            for(let i in warehouseList){
                if(warehouseList[i].code == code){
                    return warehouseList[i].name;
                }
            }
        }
        return "";
    }
    //监听提交
    form.on('submit(form-element)', function (data) {
        //向后台组装数据
        //获取头部表单数据
        let req = data.field;
        //获取附件数据
        let annexReqs = table.cache["attachmenttableid"];
        //获取库存表单信息数据
        let transferDetails = table.cache["storageproductstableid"];
        if(transferDetails.length > 0){
            for(let i in transferDetails){
                if(null == transferDetails[i].transferQuantity || transferDetails[i].transferQuantity <= 0){
                    layer.confirm("存在调拨数量为零的记录，这些记录审批后不会生成相关记录，是否删除？",
                        confirmInfo(3,6),
                        function (index) {
                            var newData = deleteTransferData(transferDetails);
                            childData = [];
                            table.reload('storageproductstableid',{data : newData});
                            layer.close(index);
                        });
                    return false;
                }
            }
        }

        req["annexReqs"] = annexReqs;
        req["transferDetails"] = transferDetails;
        let datas = JSON.stringify(req);
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:datas,
            url:"transfer/contractInitAdd",
            success:function(res){
                if(res.status == 200){
                    layer.msg("保存成功", {icon: 6});
                    setTimeout(function () {
                        //保存成功则刷新提交过来的界面 并关闭此页面
                        parent.detab("views/jsp/WarehouseManagement/transfers.jsp");
                        parent.intab("views/jsp/WarehouseManagement/transfers.jsp","调拨")
                        parent.detab("views/jsp/WarehouseManagement/tpl/emptydocument.jsp"+(id==''?'':'?id='+id));
                    },1000)
                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });

    });

    //遍历删除调拨数量为0的数据
    function deleteTransferData(transferDetails){
        for(var j = 0; j < transferDetails.length; j++){
            if(transferDetails[j].transferQuantity <= 0){
                transferDetails.splice(j, 1);
                j--;
            }
        }
        return transferDetails;
    }

    //--置空产品信息
    var colss = "";
    var cols = table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid',
        data: detailData,
        toolbar: '#storageproductstoolbar',
        cols: [[
            {field: 'productCode', width: 120, title: '产品编码', sort: true},
            {field: 'lotNo', width: 120, title: '批次号', sort: true},
            {field: 'inStoreBillNo', width: 120, title: '入库单号', sort: true},
            {field: 'warehouseName',width: 120,title: '旧仓库名称'},
            {field: 'newWarehouseName',width: 120,title: '新仓库名称', event: 'newWarehouseName',config:{"type":"select","data":warehouseNamedData}},
            {field: 'specificationCode', width: 120, title: '规格编码', sort: true},
            {field: 'contractNo', width: 120, title: '销售合同号', sort: true},
            {field: 'productUnit', width: 120, title: '产品单位', sort: true},
            {field: 'transferQuantity', width: 120, title: '调拨数量',event: 'transferQuantity',"config":{"type":"input","verify":{"type":"number"}}},
            {field: 'stockQuantity', width: 120, title: '库存数量', sort: true},
            {field: 'canTransferQuantity', width: 140, title: '允许调拨数量', sort: true},
            {field: 'salesUnitPrice', width: 120, title: '销售单价',event: 'salesUnitPrice',"config":{"type":"input","verify":{"type":"number"}}},
            {field: 'money', width: 120, title: '金额小计',event: 'money',"config":{"type":"input","verify":{"type":"number"}}},
            {field: 'costUnitPrice', width: 120, title: '成本单价',event: 'costUnitPrice',"config":{"type":"input","verify":{"type":"number"}}},
            {field: 'shareCostPrice', width: 160, title: '分摊费用单价',event: 'shareCostPrice',"config":{"type":"input","verify":{"type":"number"}}},
            {field: 'trayNumber', width: 120, title: '托盘入数', sort: true},
            {field: 'totalTray', width: 120, title: '总托盘', sort: true},
            {field: 'clientProductNo', width: 120, title: '客户货号', sort: true},
            {field: 'color', width: 120, title: '颜色', sort: true},
            {field: 'productCname', width: 120, title: '中文名称', sort: true},
            {field: 'productEname', width: 120, title: '英文名称', sort: true},
            {field: 'productCdesc', width: 120, title: '中文描述', sort: true},
            {field: 'productEdesc', width: 120, title: '英文描述', sort: true},
            {field: 'productTypeStr', width: 120, title: '产品类型', sort: true},
            {field: 'specificationExplanation', width: 120, title: '规格说明', sort: true},
            {field: 'memo', width:220, title: '备注', sort: true},
            {fixed: 'right', title: '操作', width: 110, align: 'center', toolbar: '#storageproductseditor'}
        ]],
        page: true,
        limit:50,
        height: 380
        ,done: function (res, curr, count) {
            $(warehouseNamedData).each(function (i) {
                let option = $('<option value="' + warehouseNamedData[i].code + '">' + warehouseNamedData[i].name + '</option>');
                $("select[name = 'warehousenametable']").append(option);
            })
            colss = table.render({
                elem: '#thedetail'
                ,data:childData
                ,cols: [[
                    {field: 'inStoreBillNo', title: '入库单号', sort: true},
                    {field: 'costUnitPrice', title: '入库单价', sort: true},
                    {field: 'canTransferQuantity', title: '可调拨数量', sort: true},
                    {field: 'transferQuantity', title: '调拨数量',event: 'transferQuantity',"config":{"type":"input","verify":{"type":"number"}}}
                ]]
                ,id: 'thedetailtableid'
                ,where: {
                    id:res.data.length == 0 ? "":res.data[0].id
                }
                ,height: 200
            }).config.cols;
        }
    }).config.cols;
    let aopTable = tableEdit.aopObj(cols); //获取一个aop对象
    aopTable.on('tool(storageproductstable)', function (obj) {
        let field = $(this).data('field');
        let data = obj.data;
        if (field === 'newWarehouseName') {
            obj.update({
                    "newWarehouseName": obj.value.value,
                    "newWarehouseCode": obj.value.name
                });
            layer.msg("修改成功", {icon: 6});
        }else if (field === 'transferQuantity') {
            if(!checkTransferQuantity(data.canTransferQuantity, obj.value)){
                layer.msg("调拨数量不能大与允许调拨数量", {icon: 5});
                return;
            }
            obj.update({"transferQuantity": obj.value});
            //同时更新明细调拨数量
            let oldTransferData =  table.cache["thedetailtableid"];
            if(oldTransferData.length > 0){
                for (let i in oldTransferData) {
                    if(data.stockId == oldTransferData[i].stockId){
                        oldTransferData[i].transferQuantity = obj.value;
                        table.reload('thedetailtableid',{data : oldTransferData});
                        layer.msg("修改成功", {icon: 6});
                        break;
                    }
                }
            }
        }else if(field === 'salesUnitPrice'){
            obj.update({"salesUnitPrice": obj.value});
            layer.msg("修改成功", {icon: 6});
        }else if(field === 'money'){
            obj.update({"money": obj.value});
            layer.msg("修改成功", {icon: 6});
        }else if(field === 'costUnitPrice'){
            obj.update({"costUnitPrice": obj.value});
            layer.msg("修改成功", {icon: 6});
        }else if(field === 'shareCostPrice') {
            obj.update({"shareCostPrice": obj.value});
            layer.msg("修改成功", {icon: 6});
        }
        if (obj.event === 'del') {
            layer.confirm('确认删除',confirmInfo(3, 5), function (index) {
                let oldTransferData =  table.cache["thedetailtableid"];
                //如果删除详情的当前行,则需要重新选择详情数据
                let oldData =  table.cache["storageproductstableid"];

                if(oldTransferData[0].stockId == data.stockId){
                    //字段赋值 默认取第一条
                    let tData = dataCopy(oldData[0]);
                    table.reload('thedetailtableid',{data : tData});
                }

                for (var i = 0; i < oldData.length; i++) {
                    if (oldData[i].stockId == data.stockId) {
                        oldData.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                        i--; // 如果不减，将漏掉一个元素
                        table.reload('storageproductstableid',{data : oldData});
                        break;
                    }
                }
                //obj.del();
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });
        }
    });

    var aopTables = tableEdit.aopObj(colss);
    aopTables.on('tool(thedetailtable)', function (obj) {
        var field = $(this).data('field');
        var data = obj.data;
        if (field === 'transferQuantity') {
            if(!checkTransferQuantity(data.canTransferQuantity, obj.value)){
                layer.msg("调拨数量不能大与允许调拨数量", {icon: 5});
                return;
            }
            obj.update({"transferQuantity": obj.value});
            //修改明细数据时,更新主表数据信息
            let oldTransferData =  table.cache["storageproductstableid"];
            let temp =  table.cache["thedetailtableid"];
            childData = temp;
            if(oldTransferData.length > 0){
                for (let i in oldTransferData) {
                    if(data.stockId == oldTransferData[i].stockId){
                        oldTransferData[i].transferQuantity = obj.value;
                        table.reload('storageproductstableid',{data : oldTransferData});
                        layer.msg("修改成功", {icon: 6});
                        break;
                    }
                }
            }
        }
    });

    //单击行事件
    table.on('row(storageproductstable)', function (obj) {
        let tData = dataCopy(obj.data);
        table.reload('thedetailtableid',{data : tData});
    });

    //字段赋值
    function dataCopy(data){
        let tData = [{
            stockId : data.stockId,
            inStoreBillNo : data.inStoreBillNo,
            costUnitPrice : data.costUnitPrice,
            canTransferQuantity : data.canTransferQuantity,
            transferQuantity : data.transferQuantity
        }];
        return tData;
    }

    table.on('toolbar(storageproductstable)', function (obj) {
        switch (obj.event) {
            case 'export_inventoryproducts':
                layer.open({
                    type: 2,
                    area:["80%","95%"],
                    content: 'views/jsp/WarehouseManagement/tpl/export_inventoryproducts.jsp',
                });
                break;
        };

    });

    //数据校验
    //调拨数量不能大于允许调拨数量
    function checkTransferQuantity(canTransferQuantity, transferQuantity){
        if(transferQuantity > canTransferQuantity){
            return false;
        }
        return true;
    }

    //---附件
    table.render({
        elem: '#attachment'
        , data: annexList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName', title: '文件名', fixed: true}
            , {field: 'uploadTime', title: '上传日期', fixed: true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
        , done: function (res, index, upload) {
            let data = res.data;
            for(let i in data){
                let flag = true;
                for(let j in annexList){
                    if(data[i].id == annexList[j].id){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    annexList.push(data[i]);
                }
            }
        }
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'transfer/uploadFile'
        , field: "uploadify"
        , accept: 'file'
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , parseData: function(res){
            return {
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
        , done: function (res, index, upload) {
            let data = res.data;
            for(var i in data){
                if (data[i].status) { //上传成功
                    annexList.push(data[i]);
                    var tr = $("#uploadlist").find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                    }
                });
                break;
        }
        ;
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            let xmlHttpRequest = new XMLHttpRequest();
            let url = "wjinfo/downloadfile2?filename=" + data.filePath;
            xmlHttpRequest.open('GET', url, true);
            //设置请求头
            xmlHttpRequest.setRequestHeader("Content-type", "application/json")
            xmlHttpRequest.responseType = "blob";
            xmlHttpRequest.send(null);

            xmlHttpRequest.onload = function() {
                let content = xmlHttpRequest.response;
                // 组装a标签
                let elink = document.createElement("a");

                //设置文件下载路径
                elink.download = decodeURIComponent(data.fileName);
                elink.style.display = "none";
                let blob = new Blob([content], { type: 'application/force-download' });

                //解决下载不存在文件的问题，根据blob大小判断
                if(blob.size==0){
                    layer.msg('服务器没找到此文件，请联系管理员!');
                }else{
                    elink.href = window.URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }

            }
        } else if (obj.event === 'del') {
            layer.confirm('确认删除?',
                confirmInfo(3,5), function (index) {
                    obj.del();
                    let id = data.id;
                    for (var i = 0; i < annexList.length; i++) {
                        if (annexList[i].id == id) {
                            annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                            i--; // 如果不减，将漏掉一个元素
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                    table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
                });
        }
    });

//---操作日志 新增页面操作日志为空
    let logData = [];
    table.render({
        elem: '#otherwarehouselog'
        , data: logData
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

    //时间处理 初始赋值
    function getNowFormatDate() {
        let date = new Date();
        let separator = "-";
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        let currentDate = year + separator + month + separator + strDate;
        return currentDate;
    }
    let currentDate = getNowFormatDate();
    //调拨时间
    laydate.render({
        elem: '#time',
        value: currentDate,
        isInitValue: true
    });

    //创建时间
    laydate.render({
        elem: '#createDate',
        value: currentDate,
        min: currentDate,
        max: currentDate,
        btns: ['confirm']
    });

    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }


})